"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { Layout, Card, List, Button, Spin } from "antd";
import { LikeOutlined, CommentOutlined, StarOutlined } from "@ant-design/icons";
import api from "../../utils/api";
import postCardStyles from "@/components/PostCard.module.css"; // 样式引入

const { Content } = Layout;

export default function PopularPage() {
  const [hotPosts, setHotPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchHotPosts = async () => {
      try {
        setLoading(true);
        const response = await api.get("/posts/listHot", {
          params: { pageSize: 10 },
        });
        if (response.status === 200) {
          const posts = response.data.posts || [];
          const postsWithAuthorInfo = await Promise.all(
            posts.map(async (post) => {
              try {
                const authorResponse = await api.get("/users/info", {
                  params: { id: post.authorId },
                });
                if (authorResponse.status === 200) {
                  return {
                    ...post,
                    authorDisplayName: authorResponse.data.display_name,
                  };
                }
              } catch {
                // 忽略作者信息错误
              }
              return {
                ...post,
                authorDisplayName: "未知作者",
              };
            })
          );
          setHotPosts(postsWithAuthorInfo);
        }
      } catch (error) {
        console.error("获取热帖数据失败:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchHotPosts();
  }, []);

  return (
    <Content style={{ padding: "20px", display: "flex", marginTop: "-40px" }}>
      <div
        style={{
          flex: 1,
          overflowY: "auto",
          height: "calc(100vh - 64px - 60px)",
        }}
      >
        {loading ? (
          <Spin style={{ margin: "auto", display: "block" }} />
        ) : (
          <List
            itemLayout="vertical"
            dataSource={hotPosts}
            renderItem={(item, index) => (
              <Link key={item.id} href={`/posts/${item.id}`} passHref>
                <Card
                  hoverable
                  style={{
                    width: "98%",
                    margin: "0 auto 14px",
                    marginRight: "2%",
                    cursor: "pointer",
                    borderRadius: "16px",
                  }}
                >
                  <Card.Meta
                    title={
                      <div
                        className={postCardStyles.cardMetaTitle}
                        style={{ fontSize: "22px" }}
                      >
                        #{index + 1} {item.title}
                      </div>
                    }
                    description={
                      <div className={postCardStyles.cardContent}>
                        作者：{item.authorDisplayName}
                      </div>
                    }
                  />
                  <div className={postCardStyles.cardContent}>
                    {item.content}
                  </div>
                  <div className={postCardStyles.cardActions}>
                    <Button
                      type="text"
                      icon={<LikeOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      {item.likes}
                    </Button>
                    <Button
                      type="text"
                      icon={<CommentOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      0
                    </Button>
                    <Button
                      type="text"
                      icon={<StarOutlined />}
                      className={postCardStyles.cardButton}
                    >
                      {item.favourites}
                    </Button>
                  </div>
                </Card>
              </Link>
            )}
          />
        )}
      </div>
    </Content>
  );
}
